﻿/********************************************************************************
    Copyright (C) Binod Nepal, Planet Earth Solutions Pvt. Ltd., Kathmandu.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

namespace Pes.Messaging.ApplicationLayer
{
    public static class SerialHelper
    {
        private const uint GENERIC_ALL = 0x10000000;
        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;
        private const uint GENERIC_EXECUTE = 0x20000000;
        private const int OPEN_EXISTING = 3;
        public const int INVALID_HANDLE_VALUE = -1;

        public static string[] AvilablePorts()
        {
            List<string> retVal = new List<string>();
            for (int i = 1; i <= 32; i++)
            {
                if (PortExists(i))
                {
                    retVal.Add("COM" + i.ToString());
                }
            }
            return retVal.ToArray();
        }

        private static bool PortExists(int number)
        {
            SafeFileHandle h = CreateFile(@"\\.\COM" + number.ToString(), GENERIC_READ + GENERIC_WRITE,
                0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

            bool portExists = !h.IsInvalid;

            if (portExists)
                h.Close();

            return portExists;
        }

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern SafeFileHandle CreateFile(string lpFileName, System.UInt32 dwDesiredAccess,
            System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition,
            System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

    }
}
